package com.example.reader.ui.main.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.blankj.utilcode.utils.LogUtils;
import com.example.reader.R;
import com.example.reader.net.resp.BookItem;
import com.example.reader.ui.base.BaseFragment;
import com.example.reader.ui.main.activity.MainActivity;
import com.example.reader.ui.main.adapter.BookshelfAdapter;
import com.example.reader.ui.read.ReadBookActivity;
import com.example.reader.ui.main.widget.BookshelfBookInfoWindow;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.InputStream;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * A simple {@link Fragment} subclass.
 */
public class BookshelfFragment extends BaseFragment<MainActivity> {

    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;

    @BindView(R.id.swipe_refresh)
    SwipeRefreshLayout swipe_refresh;

    @BindView(R.id.fl_linear)
    FrameLayout fl_linear;
    private ArrayList<BookItem> items;


    public BookshelfFragment() {
        // Required empty public constructor
    }

    public static BookshelfFragment newInstance() {
        return new BookshelfFragment();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View inflate = inflater.inflate(R.layout.fragment_blank, container, false);
        ButterKnife.bind(this, inflate);
        createBook();
//        initRecyc();
        initSwipe();
        return inflate;
    }

    /**
     * copy 一本书到手机内存
     */
    private void createBook() {
        File file = new File(getActivity().getExternalCacheDir(), "星辰变.txt");
        if (!file.isFile()) {
            FileOutputStream file1 = null;
            try {
                file1 = new FileOutputStream(file);
                InputStream open = getActivity().getAssets().open("xcb.txt");
                byte[] bytes = new byte[2048];
                int byteread = 0; // 读取的字节数
                while ((byteread = open.read(bytes)) != -1) {
                    file1.write(bytes, 0, byteread);
                }
                file1.close();
                open.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        File cacheDir = getActivity().getExternalCacheDir();
        File[] files = cacheDir.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File file, String s) {
                return !(file.isFile() && file.getName().endsWith(".txt"));
            }
        });
        items = new ArrayList<>();
        for (File file1 : files) {
            BookItem bookItem = new BookItem();
            bookItem.name = file1.getName().substring(0,file1.getName().indexOf("."));
            items.add(bookItem);
        }
        initRecyc();
    }

    private void initSwipe() {
        swipe_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        swipe_refresh.setRefreshing(false);
                        notice();
                    }
                }, 2000);
            }
        });
        swipe_refresh.setColorSchemeResources(R.color.app_theme_blue);
    }

    private void initRecyc() {
        recyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
        BookshelfAdapter adapter = new BookshelfAdapter(getActivity());
        adapter.setHeaderView(getHeaderView());
        adapter.setData(items);
        recyclerview.setAdapter(adapter);
        recyclerview.setVerticalScrollBarEnabled(true);
        recyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() {
            private int totalDy = 0;
            String TAG = "-----------------";

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                totalDy = getScrolledDistance(recyclerView);
                Log.i(TAG, "onScrolled: " + totalDy);
                if (totalDy > getActivity1().getToolbarHeight()) {
                    getActivity1().changeToolbarBg();
                } else {
                    getActivity1().resetToolbarBg();
                }
                super.onScrolled(recyclerView, dx, dy);
            }
        });

        adapter.setItemOnClickListener(new BookshelfAdapter.OnItemClickListener() {
            @Override
            public void onClick(View view, int position) {
                LogUtils.i("bookshelf ->onClick");
                startActivity(new Intent(getActivity(), ReadBookActivity.class));
            }
        });

        adapter.setOnItemLongClickListener(new BookshelfAdapter.OnItemLongClickListener() {
            @Override
            public void onLongClick(View view, int position) {
                BookshelfBookInfoWindow.getWindow(getActivity(), fl_linear).show();
            }
        });
    }


    /**
     * 获取 recyclerview 滑动的距离
     *
     * @param recyclerView
     * @return
     */
    private int getScrolledDistance(RecyclerView recyclerView) {
        return recyclerView.computeVerticalScrollOffset();
    }

    private View getHeaderView() {
        View headerView = getActivity().getLayoutInflater().inflate(R.layout.fragment_bookshelf_headerview, null);
        return headerView;
    }

    /**
     * 为了覆盖toolbar 所以top的通知要放到mainactivity 里边显示
     */
    private void notice() {
        getActivity1().showNotice("对不起我是假的刷新");
    }

}
